import { IRouter } from '@/router/router.d';
import routers, { constantRoutes } from '@/router/router.config';
import type { IAuthMenusRes } from '@/api/index.d';

// 拼接 子router的paht
const JoinChildRoutePath = (route: any) => {
  return route.children?.map((item: IRouter) => {
    let tmp: IRouter = { ...item };
    tmp.path = `${route.path}${tmp.path.substr(0, 1) === '/' ? tmp.path : `/${tmp.path}`}`;
    return tmp;
  })
}

// 拍平routers
const flattenRoutes = (routes: IRouter[]) => {
  let res: IRouter[] = [];

  routes.forEach((route: IRouter) => {
    const tmp: IRouter = { ...route };

    res.push(tmp);

    // 查看是否存在子级
    if (tmp.children?.length) {
      res = res.concat(flattenRoutes(JoinChildRoutePath(tmp)));
    };
  })
  return res;
}

export const useFlattenRoutes: Function = flattenRoutes;

/**
 * 判断是否有router权限
 */
function hasPermission(route: IRouter, authMenus: IAuthMenusRes[]) {
  if (route.autuKeys && route.autuKeys.length) {
    return authMenus.find(item => route.autuKeys?.includes(item.menuKey)) || false
  }

  return true
}

/**
 * 过滤 routes 数据
*/
const filterRoutes = (routes: IRouter[], authMenus: IAuthMenusRes[]) => {
  const res: IRouter[] = [];

  routes.forEach(route => {
    let tmp: IRouter = { ...route };
    const authMenu: IAuthMenusRes | boolean = hasPermission(tmp, authMenus);
    if (authMenu) {
      if (tmp.meta) {
        tmp.meta.title = authMenu !== true ? authMenu.displayName : tmp.meta.title;
      }

      if (tmp.children?.length) {
        tmp.children = filterRoutes(JoinChildRoutePath(tmp), authMenus)
      }
      res.push(tmp);
    }
  })

  return res;
}

export default (authMenus: IAuthMenusRes[]) => {
  return {
    routers: filterRoutes([...routers, ...constantRoutes], authMenus),
    flattenRouters: flattenRoutes([...routers, ...constantRoutes])
  }
}
